<template>
    <div class="setproinfo">
        <el-form :label-position="labelPosition" label-width="120px" :model="form" :rules="rules" ref="form">
            <el-form-item label="商品类目" v-if="!isEdit">
                {{categoryName.category}}>{{categoryName.type}}>{{categoryName.brand}}>{{categoryName.model}}
            </el-form-item>
            <el-form-item label="商品类目" v-if="isEdit">
                {{info.goods.category}}>{{info.goods.type}}>{{info.goods.brand}}>{{info.goods.model}}
            </el-form-item>
            <el-form-item label="商品名称" required prop="name">
                <el-input v-model="form.name" style="width: 325px" placeholder="请输入商品名称，不超过15个字"
                          :maxlength='max'></el-input>
            </el-form-item>
            <!--<el-form-item label="店内类目">
                <el-select v-model="form.shopid1" @change="firCateChoosedNormal">
                    <el-option
                            v-for="item in shopCate1"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                    </el-option>
                </el-select>
                <el-select v-model="form.innerCategoryId">
                    <el-option
                            v-for="item in shopCate2"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>-->
            <el-form-item label="新旧程度" required>
                <el-select v-model="form.oldLevel" style="width: 325px">
                    <el-option
                            v-for="item in oldDeg"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="租赁类型" class="rentTimesel" required>
                <el-select v-model="form.leaseType" style="width: 325px" @visible-change="change" @change="hasChange">
                    <el-option label="日租商品（30天及以下)" value="DAILY">
                    </el-option>
                    <el-option label="月租商品（60天，90天，180天...）" value="MONTHLY">
                    </el-option>
                </el-select>
                <br/>
            </el-form-item>
            <el-form-item label="租期" required prop="dailyLeaseDays" v-if="form.leaseType=='DAILY'">
                <el-checkbox-group v-model="form.dailyLeaseDays">
                    <el-checkbox v-for="(item,index) in rentDays1" :label="item+'天'" :key="index">
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="租期" required prop="monthlyLeaseDays" v-if="form.leaseType!=='DAILY'">
                <el-checkbox-group v-model="form.monthlyLeaseDays">
                    <el-checkbox v-for="(item,index) in rentDays2" :label="item+'天'" :key="index">
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="支付方式" required>
                *30天（含）以下租金一次性支付，60天以上租金每30天支付一次
            </el-form-item>
            <el-form-item label="违约金系数" required>
                <el-input
                        placeholder="5‰" :disabled="true" style="width: 325px">
                </el-input>
            </el-form-item>
            <el-form-item label="违约缓冲天数" required>
                <el-input
                        placeholder="1" :disabled="true" style="width: 325px">
                </el-input>
            </el-form-item>
            <!--旧版本原价设置-->
            <el-form-item label="原价（元）" required prop="originalPrice">
                <el-input v-model="form.originalPrice" style="width: 325px">
                </el-input>
            </el-form-item>
            <el-form-item label="意外保险（元）" prop="accidentInsurance">
                <el-input v-model="form.accidentInsurance" style="width: 325px">
                </el-input>
            </el-form-item>

            <el-form-item label="保险范围" v-if="JSON.stringify(cateNames)!=='{}'||JSON.stringify(info)!=='{}'" style="margin-bottom: 0;">
                <div class="tipText" v-for="item in assureItems" :key="item.id">
                    <el-checkbox v-model="item.isChecked">
                        {{item.name}}
                    </el-checkbox>
                    <el-tooltip class="item" effect="dark" :content="item.detail" placement="bottom"
                                popper-class="textTip">
                        <i class="icon fa fa-question-circle-o"></i>
                    </el-tooltip>
                </div>
            </el-form-item>
            <!--自定义保险项不上-->
            <!--<el-button type="text" style="width: 80px;margin-left: 30px;" @click="setAssure=true">自定义保险项</el-button>-->
            <!--<el-form ref="assureform" :model="assureForm"-->
            <!--style="border: 1px solid #ccc;width: 600px;height: 300px;margin: 20px;padding:70px 0 0 45px;box-sizing: border-box;display: inline-block;vertical-align: top;"-->
            <!--v-if="setAssure">-->
            <!--<el-form-item>-->
            <!--<el-input placeholder="请输入保险项名称" v-model="assureForm.name" style="width: 325px;"></el-input>-->
            <!--</el-form-item>-->
            <!--<el-form-item>-->
            <!--<el-input type="textarea" v-model="assureForm.detail" placeholder="请输入保险详细描述"-->
            <!--style="width: 515px;"></el-input>-->
            <!--</el-form-item>-->
            <!--<el-form-item>-->
            <!--<el-button type="primary" @click="addAssure">添加</el-button>-->
            <!--<el-button @click="cancelAddAssure">取消</el-button>-->
            <!--</el-form-item>-->
            <!--</el-form>-->
            <el-form-item label="特色服务" v-if="JSON.stringify(cateNames)!=='{}'||JSON.stringify(info)!=='{}'">
                <div class="tipText" v-for="item in speciItems" :key="item.id">
                    <el-checkbox v-model="item.isChecked">{{item.name}}</el-checkbox>
                    <el-tooltip class="item" effect="dark" :content="item.detail" placement="bottom"
                                popper-class="textTip">
                        <i class="icon fa fa-question-circle-o"></i>
                    </el-tooltip>
                </div>
                <br>
                <span v-if="num>=4" style="color: red;">特色服务至多勾选四项</span>
                <span v-if="num==0" style="color: red;">您还未选择特色服务，提交时会自动帮您勾选包邮速达一项</span>
            </el-form-item>

            <el-form-item label='是否支持续租' prop="renew">
            <el-checkbox v-model="form.renew" @change="handleCheckAllChange">支持续租
            </el-checkbox>
            </el-form-item>
            <el-form-item v-show="form.renew" label='请选择续租租期'>
                <div v-if="daysChecked">
                    <el-checkbox-group v-model="dailyrenewDays" @change="handleCheckedCitiesChange" v-if="form.dailyLeaseDays.length!=0">
                        <el-checkbox v-for="item in form.dailyLeaseDays" :label="item" :key="item">
                        </el-checkbox>
                    </el-checkbox-group>
                    <el-checkbox-group v-model="monthlyrenewDays" @change="handleCheckedCitiesChange" v-if="form.monthlyLeaseDays.length!=0">
                        <el-checkbox v-for="item in form.monthlyLeaseDays" :label="item" :key="item">
                        </el-checkbox>
                    </el-checkbox-group>
                </div>
                <div v-if="!daysChecked">
                    <span style="color: red;">请先选择商品租期</span>
                </div>

            </el-form-item>
            <el-form-item label="是否支持买断">
                <el-checkbox v-model="form.buyout">支持买断</el-checkbox>
            </el-form-item>
        </el-form>

        <div class="editBtn">
            <el-button @click="goNext('pro-intro')">下一步</el-button>
        </div>
    </div>
</template>
<script>
    import {getShopCate, getSpecItem, getAssure} from '@/api/normalPublish';
    import {setProInfo, getProInfo, removeProInfo} from '@/utils/storeProInfo';
    import {stripscript, isNumber, IntergerIncludeZero,isNumberZ,isIllegal} from '@/utils/validate';
    import {removeProRent} from '@/utils/storeNormalRent';

    export default {
        name: 'goodsPropInfo',
        props: {
            'categoryName': {
                type: Object,
                default: () => {
                    return {}
                }
            },
            'isEdit': {
                type: Boolean,
                default: false
            },
            'info': {
                type: Object,
                default: () => {
                    return {}
                }
            }
        },
        data() {
//            验证
            let validator = (rule, value, callback) => {
                if (isIllegal(value)) {
                    callback(new Error('请输入合法的名称'));
                }
                callback()
            };
            let validatorMoney = (rule, value, callback) => {
                if (!isNumber(value)) {
                    callback(new Error('请输入小数点后最多两位的正数!'))
                }
                callback()
            };
            let assuranceValidator = (rule, value, callback) => {
                if (!isNumberZ(value)) {
                    callback(new Error('请输入小数点后最多两位的正数!'))
                }
                callback()
            };
            return {
                max: 30,
                form: {
                    name: '',
                    dailyLeaseDays: [],
                    monthlyLeaseDays: [],
//                    deposit: 0,
                    originalPrice: 0,
                    accidentInsurance: 0,
                    oldLevel: 7,
                    buyout: false,
                    leaseType: 'DAILY',
                    renew:false
                },
                rules: {
                    name: [
                        {required: true, message: '不能为空'},
                        {validator: validator, trigger: 'blur'}
                    ],
                    rent: [
                        {required: true, message: '不能为空'},
                        {validator: validatorMoney, trigger: 'blur'}
                    ],
                    originalPrice: [
                        {required: true, message: '不能为空'},
                        {validator: validatorMoney, trigger: 'blur'}
                    ],
                    accidentInsurance: [
                        {required: true, message: '不能为空'},
                        {validator: assuranceValidator, trigger: 'blur'}
                    ],
                    dailyLeaseDays: [
                        {type: 'array', required: true, message: '请至少选择一个租期', trigger: 'change'}
                    ],
                    monthlyLeaseDays: [
                        {type: 'array', required: true, message: '请至少选择一个租期', trigger: 'change'}
                    ],
                },
                dailyrenewDays: [],
                monthlyrenewDays:[],
                selectedRentType: 'lt30',
                labelPosition: 'right',
//        待定根据 innerCategoryId 来请求接口 返回 一级和二级 分类
                shopCate1: [],
                shopCate2: [],
                oldDeg: [
                    {
                        id: 5,
                        name: '5成新'
                    },
                    {
                        id: 6,
                        name: '6成新'
                    },
                    {
                        id: 7,
                        name: '7成新'
                    },
                    {
                        id: 8,
                        name: '8成新'
                    },
                    {
                        id: 9,
                        name: '9成新'
                    },
                    {
                        id: 10,
                        name: '全新'
                    }
                ],
                assureItems: [],
                speciItems: [],
                rentDays1: [3, 5, 7, 14, 30],
                rentDays2: [60, 90, 120, 180, 360]
            }
        },
        computed: {
            num(val) {
                let t = 0;
                for (let item of this.speciItems) {
                    if (item.isChecked) {
                        t++;
                    }
                }
//                console.log(t);
                return t;
            },
            cateNames:{
                get(){
                    return this.categoryName;
                },
                set(value){
                    this.categoryName=value;
                }
            },
            daysChecked() //商品租期是否已选
            {
                return this.form.dailyLeaseDays.length > 0 || this.form.monthlyLeaseDays.length > 0;
            },
        },
        methods: {
            //            全选
            handleCheckAllChange(val){
                if(this.form.dailyLeaseDays.length){
                    this.dailyrenewDays = val ? this.form.dailyLeaseDays : [];
                }
                if(this.form.monthlyLeaseDays.length){
                    this.monthlyrenewDays = val ? this.form.monthlyLeaseDays : [];
                }

                if(!this.form.renew){
                    this.dailyrenewDays=[];
                    this.monthlyrenewDays=[];
                }
            },
            handleCheckedCitiesChange(value){
//                选择
                let checkedCount = value.length;
                this.form.renew = checkedCount != 0;
            },
            /*getFirCategory() {
                getShopCate(this.$store.getters.id)
                    .then((resp) => {
                        console.log(resp);
                        this.list = resp.data.list;
                        for (let item of this.list) {
                            let firCate = {
                                name: item.name,
                                id: item.id
                            };
                            this.shopCate1.push(firCate)
                        }
                    }).catch((err) => {
                    console.log(err)
                })
            },
            firCateChoosedNormal(value) {
//                console.log(value);
                if (value) {
                    for (let item of this.list) {
                        if (value == item.id) {
                            for (let item1 of item.children) {
                                let secCate = {
                                    name: item1.name,
                                    id: item1.id
                                };
                                this.shopCate2.push(secCate)
                            }
                        }
                    }
                }

            },*/
            change(val) {
//                触发下拉
                if (val) {
                    this.$message({
                        type: 'warning',
                        message: '更改租赁类型需要重新添加您的商品，是否继续？'
                    });

                }
            },
            hasChange(val) {
//                如果跟当前的不一样
                let oldLeaseType=this.info.goods.leaseType?this.info.goods.leaseType:this.form.leaseType;
//                console.log(oldLeaseType);
                if(val!=oldLeaseType){
                    this.renewDays=[];
                    this.form.dailyLeaseDays=[];
                    this.form.monthlyLeaseDays=[];
                    this.form.renew=false;
//                更改了租赁类型 就清空数据;
//                console.log(val);
                    removeProRent();
                    removeProInfo();
                    this.$root.eventHub.$emit("type-change", val);
                }
            },
            getAssureAndSpec() {
                if (this.isEdit) {
                    let data = {
                        categoryId: this.info.goods.categoryId,
                        typeId: this.info.goods.typeId
                    };
                    getAssure(data).then((resp) => {
//                        console.log(resp);
                        let data = resp.data;

                        for (let item of data) {
                            let insur = {
                                name: item.insuranceName,
                                id: item.id,
                                isChecked: false,
                                detail: item.detail
                            };
                            this.assureItems.push(insur)
                        }
                        if (this.info.insuranceIds) {
                            let arr = this.info.insuranceIds.split(',');
                            let item;
//                    console.log(this.assureItems);
                            for (item of arr) {
//                        console.log(item);
                                for (let items of this.assureItems) {
//                            console.log(items);
                                    if ((item - 0) == items.id) {
                                        items.isChecked = true;
                                    }
                                }
                            }
                        }

                    }).catch((err) => {
//                        console.log(err);
                    });

                    getSpecItem(data).then((resp) => {
//                        console.log(resp);
                        let data = resp.data;
                        for (let item of data) {
                            let speciItem = {
                                name: item.name,
//                            注意字段名
                                id: item.id,
                                isChecked: false,
                                detail: item.detail
                            };
                            this.speciItems.push(speciItem);
                        }

                        //特色项目和保险项
                        if (this.info.characteristicIds) {
                            let arr = this.info.characteristicIds.split(',');
//                    console.log(arr);
                            let item;
                            for (item of arr) {
//                        console.log(item);
                                for (let items of this.speciItems) {
//                            console.log(items);
                                    if ((item - 0) == items.id) {
                                        items.isChecked = true;
                                    }
                                }
                            }
                        }
                    }).catch((err) => {
//                        console.log(err)
                    });

                    setTimeout(this.renderData, 300)

                } else {
//发布的时候  有缓存则显示缓存
//                    console.log(this.categoryName);
                    let data = {
                        categoryId: this.cateNames.categoryId,
                        typeId: this.cateNames.typeId
                    };
                    getAssure(data).then((resp) => {
                            let data = resp.data;
                            for (let item of data) {
                                let insur = {
                                    name: item.insuranceName,
                                    id: item.id,
                                    isChecked: false,
                                    detail: item.detail
                                };
                                this.assureItems.push(insur)
                            }
                            if (sessionStorage.getItem('assurIds')) {
                                if (JSON.parse(sessionStorage.getItem('assurIds')).insuranceIds) {
                                    let arr = JSON.parse(sessionStorage.getItem('assurIds')).insuranceIds.split(',');
                                    let item;
                                    for (item of arr) {
                                        for (let items of this.assureItems) {
                                            if ((item - 0) == items.id) {
                                                items.isChecked = true;
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    ).catch((err) => {
//                        console.log(err)
                    });

                    getSpecItem(data).then((resp) => {
//                        console.log(resp)
                        let data = resp.data;
                        for (let item of data) {
                            let speciItem = {};
                            if (item.name == '包邮速达') {
                                speciItem = {
                                    name: item.name,
//                            注意字段名
                                    id: item.id,
                                    isChecked: true,
                                    detail: item.detail
                                };
                            } else {
                                speciItem = {
                                    name: item.name,
//                            注意字段名
                                    id: item.id,
                                    isChecked: false,
                                    detail: item.detail
                                };
                            }

                            this.speciItems.push(speciItem);
                        }
                        if (sessionStorage.getItem('specIds')) {
                            if (JSON.parse(sessionStorage.getItem('specIds')).characteristicIds) {
                                let arr = JSON.parse(sessionStorage.getItem('specIds')).characteristicIds.split(',');
//                    console.log(arr);
                                let item;
                                for (item of arr) {
//                        console.log(item);
                                    for (let items of this.speciItems) {
//                            console.log(items);
                                        if ((item - 0) == items.id) {
                                            items.isChecked = true;
                                        }
                                    }
                                }
                            }
                        }


                    }).catch((err) => {
//                        console.log(err)
                    });
//                    console.log(getProInfo());
                    if (JSON.stringify(getProInfo()) != '{}') {
                        this.form = {
                            "name": getProInfo().name,
                            "dailyLeaseDays": getProInfo().leaseType == 'DAILY' ? getProInfo().leaseDays : [],
                            'monthlyLeaseDays': getProInfo().leaseType !== 'DAILY' ? getProInfo().leaseDays : [],
//                    "deposit": this.info.goods.deposit,
                            "originalPrice": getProInfo().originalPrice,
                            "accidentInsurance": getProInfo().accidentInsurance,
                            "oldLevel": getProInfo().oldLevel - 0,
                            "buyout": getProInfo().buyout,
                            "leaseType": getProInfo().leaseType
                        };
                    }
                }
            },
            save() {
//                console.log('save proinfo data');
                let arr1 = [];
                for (let item of this.assureItems) {
                    if (item.isChecked) {
//                        被勾选
                        arr1.push(item.id);
                    }
                }
                let str1 = arr1.join();
                let group3 = {
                    "insuranceIds": str1
                };
                //                特色项
                let arr2 = [];
                for (let item of this.speciItems) {
                    if (item.isChecked) {
//                        被勾选
                        arr2.push(item.id)
                    }

                }
                if (arr2.length > 4) {
                    this.$message({
                        type: 'warning',
                        message: '特色服务至多勾选四项,请重新勾选，否则不予修改'
                    });
                }
                //                        如果一项都没有选

                if (!arr2.length) {
                    for (let item of this.speciItems) {
                        if (item.name == '包邮速达') {
                            item.isChecked = true;
                            arr2.push(item.id);
                        }
                    }
                }
//                console.log(arr2);
                let str2 = arr2.join();
//                console.log(str2);
                let group4 = {
                    "characteristicIds": str2
                };

                let goodsInfo = {
                    categoryId: this.categoryName.categoryId,
                    typeId: this.categoryName.typeId,
                    brandId: this.categoryName.brandId,
                    modelId: this.categoryName.modelId,
                };

                let form = {
                    "name": this.form.name,
                    "leaseDays": this.form.leaseType == 'DAILY' ? this.form.dailyLeaseDays : this.form.monthlyLeaseDays,
//                    "deposit": this.info.goods.deposit,
                    "originalPrice": this.form.originalPrice,
                    "accidentInsurance": this.form.accidentInsurance,
                    "oldLevel": this.form.oldLevel,
                    "buyout": this.form.buyout,
                    "leaseType": this.form.leaseType,
                    "renew":this.form.renew,
                    "renewDays":this.form.leaseType == 'DAILY' ?this.dailyrenewDays:this.monthlyrenewDays
                };
//                console.log(form.renewDays);
                if(!form.leaseDays.length){
                    this.$message.error('请选择租期！');
                }
                //新增保险项 不上
                // let newAssure={};
                // if(this.newAssureItems.length){
                //
                //     newAssure={
                //         addAssureItems:[]
                //     };
                //     for(let item of this.newAssureItems){
                //         if(item.isChecked){
                //             let a={
                //                 name:item.name,
                //                 detail:item.detail
                //             };
                //             newAssure.addAssureItems.push(a);
                //         }
                //     }
                //     setAssures(newAssure);
                // }
                this.$refs.form.validate((valid) => {
                    if (valid) {
//                        console.log(Object.assign({}, this.form,group3,group4,goodsInfo))
                        if (this.isEdit) {
                            setProInfo(Object.assign({}, form, goodsInfo, {id: this.info.goods.id}))
                        } else {
                            setProInfo(Object.assign({}, form, goodsInfo));
                        }
                        sessionStorage.setItem('assurIds', JSON.stringify(group3));
                        sessionStorage.setItem('specIds', JSON.stringify(group4));
                    }
                });
            },
            goNext(stepName) {
                this.save();
                this.$emit('nextprew', stepName);
            },
            renderData() {
//                console.log(this.info);
                let arrDay = this.info.goods.leaseDays ? this.info.goods.leaseDays.split(',').map((item) => {
                    return item + '天'
                }) : [];
//                console.log(arrDay);
                this.form = {
                    "name": this.info.goods.name,
                    "dailyLeaseDays": this.info.goods.leaseType == 'DAILY' ? arrDay : [],
                    'monthlyLeaseDays': this.info.goods.leaseType == 'MONTHLY' ? arrDay : [],
//                    "deposit": this.info.goods.deposit,
                    "originalPrice": this.info.goods.originalPrice / 100,
                    "accidentInsurance": this.info.goods.accidentInsurance / 100,
                    "oldLevel": this.info.goods.oldLevel - 0,
                    "buyout": this.info.goods.buyout,
                    "leaseType": this.info.goods.leaseType,
                    "renew":this.info.goods.renew
                };
//                console.log(this.form);
                if(this.info.goods.leaseType=='DAILY'){
                    this.dailyrenewDays=this.info.goods.renewDays.split(',').length ? this.info.goods.renewDays.split(',').map(item => {
                        return item + '天'
                    }) : [];
                }
                if(this.info.goods.leaseType=='MONTHLY'){
                    this.monthlyrenewDays=this.info.goods.renewDays.split(',').length ? this.info.goods.renewDays.split(',').map(item => {
                        return item + '天'
                    }) : [];
                }
            },
            backToPublish() {
                this.$confirm('此操作将丢失编辑的数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    clearSession();
                    this.$router.push({path: '/goods/publish'})
                }).catch(() => {

                });
            },
            addAssure() {
//                 添加保险项  点击后框框消失 assureitem里push一组数据
                if (!this.assureForm.name || !this.assureForm.detail) {
                    this.$message.error('请填写完整保险项');
                    return;
                }
                if (isIllegal(this.assureForm.name)) {
//                    不合法
                    this.$message.error('保险项名称请勿填写非法字符');
                    return;
                }
                if (isIllegal(this.assureForm.detail)) {
//                    不合法
                    this.$message.error('保险项描述请勿填写非法字符');
                    return;
                }

                let temp={
                    name: this.assureForm.name,
//                            注意字段名
                    isChecked: true,
                    detail: this.assureForm.detail,
                };
                this.assureItems.push(temp);
                this.newAssureItems.push(temp);
                this.assureForm = {};
            },
            cancelAddAssure() {
                this.setAssure = false;
                this.assureForm = {};
            },
        },
        mounted() {
            setTimeout(this.getAssureAndSpec, 300);
//            this.getFirCategory();

        },
    }
</script>

<style lang="less">
    .setproinfo {
        .el-form {
            .el-form-item {
                .el-form-item__content {
                    width: 880px;
                }

            }
        }
        .tipText {
            display: inline-block;
            margin: 0 10px;
        }
        .el-tooltip__popper {
            &.is-light {
                background: transparent;
                border: none;
                color: red;
                .popper__arrow {
                    display: none;
                }
            }

        }
        .editBtn {
            display: block;
            text-align: center;
            margin-top: 24px;

        }
    }
</style>
